/*
 * @Author: Dufen~123 dufen.0
 * @Date: 2024-12-26 15:30:46
 * @LastEditors: Dufen~123 dufen.0
 * @LastEditTime: 2024-12-26 16:09:12
 * @FilePath: \my-app\src\components\commonAside\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React from "react";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { selectMenuList } from "../../store/reducers/tab";
import ConfigMenu from "../../config"; //把config对象引入进来
import * as Icon from "@ant-design/icons"; //图标
import { Layout, Menu } from "antd";
const { Sider } = Layout; //Sider是Layout里面的组件
const iconToElement = (name) => React.createElement(Icon[name]);
//根据传入的 name 参数动态创建并返回一个 React 元素
//因为我们在React中只能操作React元素，上面的方法就动态地创建了React元素
const items = ConfigMenu.map((item) => {
  //呈现一级菜单
  const child = {
    key: item.path,
    icon: iconToElement(item.icon),
    label: item.label,
  };
  //   console.log(child)
  //呈现二级菜单
  if (item.children) {
    child.children = item.children.map((itemchild) => {
      return {
        key: itemchild.path,
        icon: iconToElement(itemchild.icon),
        label: itemchild.label,
      };
    });
  }
  // console.log(child.children)
  return child;
});
// console.log(items)

const CommonAside = ({ collapse }) => {
  const Navigate = useNavigate(); //跳转路由
  const dispatch = useDispatch(); //调用store中的reducer
  //添加数据到store 
  const setTableList = (val) => {
    dispatch(selectMenuList(val));
  };
  //点击菜单
  const selectMenu = (e) => {
    // console.log("点击的菜单", e);
    let data;
    ConfigMenu.forEach((item) => {
      if (item.path === e.keyPath[e.keyPath.length - 1]) {
        //找第一层
        data = item;
        // console.log("一级路由", item);
      }
      if (e.keyPath.length > 1) {
        //不止一层就找点击的那个子路由，也就是第二层
        // console.log("二级路由", item.children);
        if (data && data.children) {
          data = data.children.find((child) => child.path === e.key);
        }
        // data = data && item.children.find((child) => child.path === e.key);
        //一定要加个data &&确保data不是undefined
        //find()就是找到一个数值中return为true的项
      }else{
        data = item;
      }
    });
    //整理tabList的数据
    setTableList({
      path: data.path,
      name: data.name,
      label: data.label,
    });
    const id = 123; 
    Navigate(e.key); //e.key就是路径，Navigate是用来跳转路径的
    // Navigate(`${e.key}/${id}`);
    // Navigate(`${e.key}?id=${id}`);
  }; //这个方法一定要写在组件函数里，因为用到了勾子函数
  return (
    <Sider trigger={null} collapsible collapsed={collapse}>
      <h3 style={{ color: "white", height: 20, marginTop: 10 }}>
        通用后台管理系统
      </h3>
      <Menu
        theme="dark"
        mode="inline"
        defaultSelectedKeys={["1"]}
        items={items}
        onClick={selectMenu}
      />
    </Sider>
  );
};
export default CommonAside;
